package com.rpoonolly.simplegame;

import java.util.List;
import java.util.Map;

import javax.vecmath.Vector2d;

import android.content.Context;
import android.content.res.Resources;

import com.rpoonolly.simpleandroidgame.R;
import com.rpoonolly.simplegame.core.CollisionDetector;
import com.rpoonolly.simplegame.core.CollisionResponder;
import com.rpoonolly.simplegame.core.aabb.AABBCollision;
import com.rpoonolly.simplegame.core.aabb.AABBEntity;
import com.rpoonolly.simplegame.core.aabb.DynamicAABBEntity;

public class SimpleEnemyProcessor extends SimpleCharacterProcessor {
	private long lastTime;
	private Context context;
	
	public SimpleEnemyProcessor(
			CollisionDetector<AABBEntity, AABBCollision> detector,
			CollisionResponder<AABBCollision> responder) {
		super(detector, responder);
	}

	@Override
	public void process(Map<String, List<AABBEntity>> gameWorld) {
		
		if (lastTime == 0) lastTime = System.currentTimeMillis();
		long dt = System.currentTimeMillis() - lastTime;
		lastTime += dt;
		
		List<AABBEntity> worldObjs = gameWorld.get(Config.ENT_GRP_WORLD_OBJS);
		DynamicAABBEntity player = (DynamicAABBEntity) gameWorld.get(Config.ENT_GRP_PLAYER).get(0);
		List<AABBEntity> enemies = gameWorld.get(Config.ENT_GRP_ENEMIES);
		
		DynamicAABBEntity enemy_dynamic;
		Vector2d v;
		AABBCollision minCollision;
		double dx, dy;
		for(AABBEntity enemy : enemies) {
			enemy_dynamic = (DynamicAABBEntity) enemy;
			v = enemy_dynamic.getDirection();
			v.x = 0;
			v.y = 0;
			
			dx = player.getX() - enemy_dynamic.getX();
			dy = player.getY() - enemy_dynamic.getY();
			
			if (dx != 0 && dy != 0) {
				if (Math.abs(dx) > Math.abs(dy)) {
					v.x = Config.ENEMY_MAX_SPEED * dt / 1000;
					v.y = v.x * Math.abs(dy / dx);
				} else {
					v.y = Config.ENEMY_MAX_SPEED * dt / 1000;
					v.x = v.y * Math.abs(dx / dy);
				}
				
				if (dx < 0) v.x *= -1;
				if (dy < 0) v.y *= -1;
			}
			
			minCollision = checkWorldCollision(enemy_dynamic, worldObjs);
			if (minCollision != null)
				v = collisionResponder.collisionRespond(minCollision);
			
			enemy.setX((int) (enemy.getX() + v.x));
			enemy.setY((int) (enemy.getY() + v.y));
		}
	}

}
